# 系统工具上传api
import os
from web.ais.TengXunYuanBao import ImageEdit
from django.http import JsonResponse
from django.conf import settings


TengXunYuanBao_ImageUpdate = ImageEdit.TengXunYuanBao_ImageEdit()

# 上传文件公共函数
def public_upload_file(file_body, save_path):
    # 获取项目的根路径
        base_dir = settings.BASE_DIR
        # 构建到 user_update_img 目录的路径
        user_update_img_path = os.path.join(base_dir, 'media', save_path)
        if not os.path.exists(user_update_img_path):
            os.makedirs(user_update_img_path)

        # 保存文件到 user_update_img 目录
        # 路径
        img_file_path = os.path.join(user_update_img_path, file_body.name)
        with open(img_file_path, 'wb') as destination:
            for chunk in file_body.chunks():
                destination.write(chunk)

        # 删除文件
        # if os.path.exists(img_file_path):
        #     os.remove(img_file_path)

        return img_file_path
       
        

def upload_img(request):
    if request.method == 'POST':
        file = request.FILES['file']
        img_file_path = public_upload_file(file, 'user_update_img')

        responses = TengXunYuanBao_ImageUpdate.upload_image(img_file_path)
        # 删除文件
        if os.path.exists(img_file_path):
            os.remove(img_file_path)

        # 判断 responses 是否有某个key
        if responses.get("response") is not None:
            responses['code'] = 200
            return JsonResponse(responses, status=200, safe=False)
        else:
            return JsonResponse({"code": 400}, status=400, safe=False)

    return JsonResponse({'error': '无效的请求'}, status=400)



def upload_file(request):
    if request.method == 'POST':
        file = request.FILES['file']
        img_file_path = public_upload_file(file, 'user_update_file')
        return JsonResponse({"code": 200, "file_path": img_file_path}, status=200, safe=False)

    return JsonResponse({'error': '无效的请求'}, status=400)

